package com.sk.waste.app.activitys

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.FrameLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.annotations.LCBindViewOnclick
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCDeviceUtil
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.waste.app.R
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseActiivity
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.models.UserModel
import com.sk.waste.app.utils.LoginUtil
import com.sk.waste.app.utils.OkHttpUtil
import com.sk.waste.app.utils.PermissionUtil
import com.sk.waste.app.views.ProvacyPopuWindow
import com.sk.waste.app.views.SkAlertDialog
import okhttp3.Call
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException

/**
 *  @time 2025/4/25  17:11
 *  @desc 登录
 */
class LoginActivity : BaseActiivity() {

    @LCBindView(R.id.ac_root_view)
    private lateinit var rootView: ConstraintLayout

    @LCBindView(R.id.ac_login_user)
    private lateinit var etvUser: TextView

    @LCBindView(R.id.ac_login_password)
    private lateinit var etvPass: TextView

    @LCBindView(R.id.ac_login_submit)
    private lateinit var bttLogin: Button

    @LCBindView(R.id.ac_login_register)
    private lateinit var ttvRegister: TextView

    @LCBindView(R.id.ac_login_resetpass)
    private lateinit var ttvRestPaww: TextView

    @LCBindView(R.id.ac_login_checkbox)
    private lateinit var checkBox: CheckBox

    @LCBindView(R.id.ac_login_privacy)
    private lateinit var ttvPrivacy: TextView

    @LCBindView(R.id.ac_login_agreement)
    private lateinit var ttvAgreement: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_login)
        super.onCreate(savedInstanceState)
        setTitleColorLight(false)
//        PermissionUtil.instance.requesetPermission(this)
        setOnclickListener()
        aotuLogin()
        Handler(Looper.getMainLooper()).postDelayed({
            showAlertDialog()
        }, 2000)
    }

//    /**
//     *  @time 2024/10/8  9:49
//     *  @author Im_jingwei
//     *  @desc app请求权限回调
//     */
//    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        PermissionUtil.instance.onRequestPermissionsResult(requestCode, permissions, grantResults)
//    }

    private fun setOnclickListener() {

        bttLogin.setOnClickListener {
            loginOnline()
        }

        ttvRegister.setOnClickListener {
            val intent = Intent(mContext, RegisterActivity::class.java)
            startActivity(intent)
        }

        ttvRestPaww.setOnClickListener {
//            val intent = Intent(mContext, ResetPassActivity::class.java)
            val intent = Intent(mContext, FindPassActivity::class.java)
            startActivity(intent)
        }

        checkBox.setOnCheckedChangeListener { compoundButton, b ->
            if (b) {
                LCSPUtil.save(mContext, AppConfig.SP_USER_AGREEMENT, "1")
                LCSPUtil.save(mContext, AppConfig.SP_USER_PROVACY, "true")
            } else {
                LCSPUtil.save(mContext, AppConfig.SP_USER_AGREEMENT, "0")
            }
        }

        ttvPrivacy.setOnClickListener {
            val intent = Intent(mContext, WebViewActivity::class.java)
            val url = "http://waste.biddingcloud.cn/privacy_agreement.html"
            intent.putExtra("extral_title", "用户隐私协议")
            intent.putExtra("extral_path", url)
            startActivity(intent)
        }

        ttvAgreement.setOnClickListener {
            val intent = Intent(mContext, WebViewActivity::class.java)
            val url = "http://waste.biddingcloud.cn/register_agreement.html"
            intent.putExtra("extral_title", "用户注册协议")
            intent.putExtra("extral_path", url)
            startActivity(intent)
        }
    }

    /**
     *  @time 2024/10/29  17:09
     *  @author Im_jingwei
     *  @desc 自动登录
     */
    private fun aotuLogin() {
        if (LCDeviceUtil.hasNetWork(mContext)) {
            val userAccount = LCSPUtil[mContext, AppConfig.SP_USER_ACCOUNT]
            val userPass = LCSPUtil[mContext, AppConfig.SP_USER_PASSWORD]
            if (!TextUtils.isEmpty(userAccount) && isAreement()) {
                etvUser.text = userAccount
                etvPass.text = userPass
                checkBox.isChecked = true
                loginOnline()
            }
        } else {
            showToast("没有网络，请检测网络情况！")
        }
    }

    /**
     *  @time 2025/6/6  14:50
     *  @author Im_jingwei
     *  @desc 是否已勾选用户协议
     */
    private fun isAreement(): Boolean {
        val userAgreement = LCSPUtil[mContext, AppConfig.SP_USER_AGREEMENT]
        if (userAgreement != null && !TextUtils.isEmpty(userAgreement) && userAgreement == "1") {
            return true
        } else {
            return false
        }
    }

    private fun loginOnline() {
        val userStr = etvUser.text.toString()
        val passStr = etvPass.text.toString()
        if (TextUtils.isEmpty(userStr)) {
            showToast("请输入用户名！")
            return
        }
        if (TextUtils.isEmpty(passStr)) {
            showToast("请输入密码！")
            return
        }
        if (!checkBox.isChecked) {
            showToast("请仔细阅读并勾选《隐私协议》及《用户协议》！")
            return
        }
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_LOGIN
        val json = JSONObject()
        json.put("account", userStr.trim())//用户名称
        json.put("password", passStr.trim())//用户密码
        LCSPUtil.save(mContext, AppConfig.SP_USER_PASSWORD, passStr.trim())
//        loginSubmit(mContext, url, json.toString())
        LoginUtil.loginSubmit(1,this, url, json.toString(), loginCallBack)
    }

    private val loginCallBack = object : LCInterface.LcCallBack {
        override fun callBack(vararg args: Any?) {
            toMain()
        }
    }

    private fun toMain() {
        Thread.sleep(500)
        cancleProgress()
        val intent = Intent(mContext, MainActivity::class.java)
        startActivity(intent)
        finish()
    }

    /**
     *  @time 2025/5/9  17:53
     *  @desc 隐私提醒
     */
    private fun showAlertDialog() {
        val isShowProvacy = LCSPUtil[mContext, AppConfig.SP_USER_PROVACY]
        if (!LCBaseUtil.isNull(isShowProvacy)) {
            return
        }
        val provacyPopuWindow = ProvacyPopuWindow()
        provacyPopuWindow.init(this)
        provacyPopuWindow.setPopuOnclickListener(object : LCInterface.LcCallBack {
            override fun callBack(vararg args: Any?) {
                val agreement = args[0] as Boolean
                if (agreement) {
                    LCSPUtil.save(mContext, AppConfig.SP_USER_PROVACY, "true")
                } else {
                    showAlert()
                }
            }
        })
        provacyPopuWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0)
    }

    /**
     *  @time 2025/5/9  17:53
     *  @desc 显示拒绝提示
     */
    private fun showAlert() {
        val cacheDialog = SkAlertDialog(mContext)
        cacheDialog.setOnclickListener(object : LCInterface.LcOnPnButtonClickLitener {
            override fun onNegetiveClick(vararg args: Any?) {
            }

            override fun onPositiveClick(vararg args: Any?) {
            }
        })
        cacheDialog.setTitleAndContent("用户提醒", "您已拒绝用户隐私协议，我们无法继续向您提供优质服务，如需继续使用请勾选页面下方的《隐私协议》及《用户协议》。")
        cacheDialog.showExpend()
    }

}